// plotly.js
var w = window.innerWidth;
var truewidth = w > 1000 ? w * 0.595 : w * 0.9;

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}

function getFirstDayOfMonth(date) {
    var d = new Date(date);
    d.setDate(1);
    return formatDate(d);
}

function getCurrentYear(date) {
    var d = new Date(date);
    d.setMonth(0);
    d.setDate(1);
    return formatDate(d);
}

var currentDate = new Date();
var firstDayOfThisMonth = getFirstDayOfMonth(currentDate);
var thisYear = getCurrentYear(currentDate);
var oneWeekAgo = new Date(currentDate);
oneWeekAgo.setDate(currentDate.getDate() - 7);
var oneMonthAgo = new Date(currentDate);
oneMonthAgo.setDate(currentDate.getDate() - 30);
var threeMonthAgo = new Date(currentDate);
threeMonthAgo.setDate(currentDate.getDate() - 90);

document.addEventListener('DOMContentLoaded', function() {
    // 检测是否为移动设备
    const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    
    // 初始化图表，默认显示一个月的数据
    loadChartData('month');

    // 为按钮添加点击事件监听器
    document.querySelectorAll('.btn-group .btn').forEach(button => {
        button.addEventListener('click', function() {
            // 移除所有按钮的选中状态
            document.querySelectorAll('.btn-group .btn').forEach(btn => btn.classList.remove('active'));
            // 为当前按钮添加选中状态
            this.classList.add('active');

            // 根据按钮的 data-period 属性加载相应的数据
            const period = this.getAttribute('data-period');
            if (period === 'week') {
                loadChartData(formatDate(oneWeekAgo));
            } else if (period === 'month') {
                loadChartData(formatDate(oneMonthAgo));
            } else if (period === '3month') {
                loadChartData(formatDate(threeMonthAgo));
            } else if (period === 'this-month') {
                loadChartData(formatDate(firstDayOfThisMonth));
            } else if (period === 'year') {
                loadChartData(formatDate(thisYear));
            } else if (period === 'all') {
                loadChartData('all');
            }
        });
    });
});

function loadChartData(period = 'month') {
    const url = `/search_NetAssetValue?time_param=${period}`;
    fetch(url)
        .then(response => response.json())
        .then(data => {
            const trace = {
                x: data.map(obj => obj.sdate),
                y: data.map(obj => obj.sNetAssetValue),
                type: 'scatter',
                mode: 'lines+markers',
                line: {
                    color: '#ffffff',
                    width: 2,
                    smoothing: 0.9
                },
                marker: {
                    color: '#ffffff',
                    size: 4
                }
            };

            const layout = {
                paper_bgcolor: 'rgba(0,0,0,0)',
                plot_bgcolor: 'rgba(0,0,0,0)',
                xaxis: {
                    type: 'date',
                    tickformat: '%Y年%m月%d日',
                    gridcolor: 'rgba(255,255,255,0.1)',
                    linecolor: 'rgba(255,255,255,0.2)',
                    tickfont: {
                        color: '#ffffff',
                        size: 10
                    },
                    automargin: true
                },
                yaxis: {
                    gridcolor: 'rgba(255,255,255,0.1)',
                    linecolor: 'rgba(255,255,255,0.2)',
                    tickfont: {
                        color: '#ffffff',
                        size: 10
                    },
                    automargin: true
                },
                showlegend: false,
                dragmode: false,
                clickmode: 'event+select',
                autosize: true,
                margin: {
                    l: 60,
                    r: 60,
                    t: 30,
                    b: 60,
                    pad: 5
                },
                width: truewidth - 80
            };

            Plotly.newPlot('plotly-chart', [trace], layout, {
                responsive: true,
                displayModeBar: false
            });
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

// 监听窗口大小变化
window.addEventListener('resize', function() {
    w = window.innerWidth;
    truewidth = w > 1000 ? w * 0.595 : w * 0.9;
    Plotly.relayout('plotly-chart', {
        width: truewidth - 80,
        autosize: true
    });
});
